package org.jeecg.word;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Hex;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jeecg.modules.demo.ipds.entity.dto.CalculatedValueDto;
import org.jeecg.modules.demo.ipds.entity.vo.SpecKeyValueDO;
import org.jeecgframework.poi.word.WordExportUtil;
import org.jeecgframework.poi.word.entity.WordImageEntity;
import org.junit.Test;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

import static org.jeecg.modules.demo.util.HttpImgUtils.getNetImgByUrl;


public class WordDao {

    @Test
    public void sjafaf() throws JsonProcessingException {
//        String a ="[{key=新的字段, value=一百, type=null, annotation=null}]";
        List<SpecKeyValueDO> a = new LinkedList<>();
        SpecKeyValueDO specKeyValueDO = new SpecKeyValueDO();
        specKeyValueDO.setKey("新的字段");
        specKeyValueDO.setValue("一百");
        a.add(specKeyValueDO);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(a);
        System.out.println(json);



        List<SpecKeyValueDO> specKeyValueDOS = JSONObject.parseArray(json, SpecKeyValueDO.class);
        System.out.println(specKeyValueDOS);

//        System.out.println(json);
    }

    @Test
    public void intsum(){
        String a = "100.11";
        String newA =a;
        //判断是个几位小数
        int jiweixiaoshu = 0;
        int xiaoshu=   a.indexOf(".")+ 1;
        if (xiaoshu!=0){
            double d = Double.valueOf(a);
            jiweixiaoshu= a.length()-xiaoshu;
           int jisuan= (int) (d*Math.pow(10,jiweixiaoshu));
            newA=String.valueOf(jisuan);
        }
        System.out.println(newA);
        System.out.println(jiweixiaoshu);


    }


    @Test
    public void fg(){
        String type = "random";
        String valueScope = "100,101";
        // 拆分字符串
        List<String> list = Arrays.asList(valueScope.split(","));
        for (int i = 0; i <100 ; i++) {

            if (CalculatedValueDto.calculatedValueTypeEnum.MAX.getType().equals(type)){
                int value = Integer.parseInt(list.get(1));
                System.out.println(value);
            }

            if (CalculatedValueDto.calculatedValueTypeEnum.MIN.getType().equals(type)){
                int value = Integer.parseInt(list.get(0));
                System.out.println(value);
            }
            if (CalculatedValueDto.calculatedValueTypeEnum.random.getType().equals(type)){
                Random random = new Random();

                int minValue = Integer.parseInt(list.get(0));
                int maxValue = Integer.parseInt(list.get(1));

                int value = random.nextInt(maxValue-minValue+1) + minValue;
                System.out.println(value);
            }
        }
    }
    public static String str2HexStr(String str, boolean lowerCase, String charset) throws UnsupportedEncodingException {
        return Hex.encodeHexString(str.getBytes(charset), lowerCase);
    }
    @Test
    public void bigMode() throws UnsupportedEncodingException {
        String hex = String.format("%02X", 255); // 得到 "ff"
        String hex2 = String.format("%02X", 55);  // 得到 "80"
        System.out.println(hex + hex2); // 输出 "ff80"
    }

    @Test
   public void sum(){
        double d = 305419896;
        String string = decimalToHex2(d);

        System.out.println(string);
        String string1 = decimalToBigEndianHex(d);
        System.out.println(string1);
        String string2 = decimalToLittleEndianHex(d);
        System.out.println(string2);
//        System.out.println(substring);

//        int decimalPart = Integer.d % 10;
    }
    public static String decimalToLittleEndianHex(double decimal) {
        long intPart = (long) decimal; // 整数部分
        double fracPart = decimal - intPart; // 小数部分

        // 将整数部分和小数部分分别转换为小端模式的十六进制
        String intHex = Long.toHexString(intPart);
        String fracHex = convertFractionToHex(fracPart);

        // 合并整数部分和小数部分的十六进制字符串，并调整为小端模式
        StringBuilder littleEndianHex = new StringBuilder(reverseHexString(intHex));
        if (!fracHex.isEmpty()) {
            littleEndianHex.append(".");
            littleEndianHex.append(reverseHexString(fracHex));
        }

        return littleEndianHex.toString().toUpperCase();
    }

    private static String convertFractionToHex(double fraction) {
        StringBuilder hexString = new StringBuilder();

        while (fraction > 0) {
            fraction *= 16;
            int digit = (int) fraction;
            hexString.append(Integer.toHexString(digit));
            fraction -= digit;
        }

        return hexString.toString();
    }

    private static String reverseHexString(String hexString) {
        StringBuilder reversed = new StringBuilder();
        for (int i = hexString.length() - 2; i >= 0; i -= 2) {
            reversed.append(hexString.substring(i, i + 2));
        }
        return reversed.toString();
    }

    public static String decimalToBigEndianHex(double decimal) {
        long intPart = (long) decimal; // 整数部分
        double fracPart = decimal - intPart; // 小数部分

        // 将整数部分和小数部分分别转换为大端模式的十六进制
        String intHex = Long.toHexString(intPart);
        String fracHex = convertFractionToHex(fracPart);

        // 合并整数部分和小数部分的十六进制字符串
        StringBuilder bigEndianHex = new StringBuilder(intHex);
        if (!fracHex.isEmpty()) {
            bigEndianHex.append(".");
            bigEndianHex.append(fracHex);
        }

        return bigEndianHex.toString().toUpperCase();
    }

//    private static String convertFractionToHex(double fraction) {
//        StringBuilder hexString = new StringBuilder();
//
//        while (fraction > 0) {
//            fraction *= 16;
//            int digit = (int) fraction;
//            hexString.append(Integer.toHexString(digit));
//            fraction -= digit;
//        }
//
//        return hexString.toString();
//    }

    public static String decimalToHex2(double decimal) {
        int intPart = (int) decimal;
        double fracPart = decimal - intPart;

        StringBuilder hexInt = new StringBuilder(Integer.toHexString(intPart));

        StringBuilder hexFrac = new StringBuilder();
        while (fracPart > 0) {
            fracPart *= 16;
            int digit = (int) fracPart;
            hexFrac.append(Integer.toHexString(digit));
            fracPart -= digit;
        }

        if (hexFrac.length() > 0) {
            return hexInt.toString().toUpperCase() + "." + hexFrac.toString().toUpperCase();
        } else {
            return hexInt.toString().toUpperCase();
        }
    }



    public void zsdadsa(String string){
        if (string.contains(".")){
            String substring = string.substring(string.indexOf(".")+1);
            double newString = Double.valueOf(substring)*16;
        }

    }


    public static String decimalToHex(double decimal) {
        // 将小数乘以一个足够大的数（例如10000），使其变为整数
        long integerPart = Double.valueOf(String.format("%.0f", decimal * 10000)).longValue();
        String hexString = Integer.toHexString(Math.toIntExact(Long.valueOf(integerPart)));
        // 恢复原来的小数部分（这里假设我们乘以了10000）
        double fractionalPart = (decimal - (integerPart / 10000)) * 10000;
        // 拼接整数部分和小数部分的十六进制表示（这里简化处理，只取整数部分的小数点后几位）
        return hexString + "." + String.format("%04d", (long) fractionalPart);
    }


    public static String convertDecimalToHexBigEndian(Integer decimalNumber) {
        // 使用Integer.toHexString确保得到正确的十六进制表示
        String hex = Integer.toHexString(decimalNumber);
//        // 由于Integer.toHexString返回的是小端模式的字符串，我们需要反转它以得到大端模式
//        StringBuilder sb = new StringBuilder(hex);
//        for (int i = 0; i < sb.length() / 2; i++) {
//            char temp = sb.charAt(i);
//            sb.setCharAt(i, sb.charAt(sb.length() - 1 - i));
//            sb.setCharAt(sb.length() - 1 - i, temp);
//        }
        return hex.toString();
    }


    public static String convertDecimalToHexBigEndian(Float  decimalNumber) {
        long bits = Float.floatToRawIntBits(decimalNumber); // 获取浮点数的位表示
        String hexRepresentation = Long.toHexString(bits); // 转换为十六进制字符串
        return hexRepresentation.toString();
    }

    public static String convertDecimalToHexBigEndian(double  decimalNumber) {
        // 分离整数部分和小数部分
        int integerPart = (int) decimalNumber;
        double fractionalPart = decimalNumber - integerPart;

        // 转换整数部分为十六进制字符串
        String intHex = Integer.toHexString(integerPart);

        // 由于小数部分不能直接转换为十六进制，我们需要将其乘以一个适当的基数（如16的幂），然后取整，再转换结果为十六进制字符串
        StringBuilder hexFractional = new StringBuilder();
        for (int i = 0; i < 1; i++) { // 这里假设我们想要保留足够的小数位数，可以根据需要调整循环次数
            double temp = fractionalPart * Math.pow(16, i);
            int tempInt = (int) (temp + 0.5); // 加0.5是为了四舍五入
            if (tempInt != 0) { // 如果转换后的值不为0，则添加到结果中
                hexFractional.append(Integer.toHexString(tempInt));
            } else {
                hexFractional.append("0"); // 如果为0，则添加一个零字符，以保持格式一致
            }
        }

        // 合并整数部分和小数部分的十六进制字符串（注意处理小数部分的格式）
        return intHex + "." + formatFractionalHex(hexFractional);
    }

    private static String formatFractionalHex(StringBuilder hexFractional) {
    // 这里可以根据需要调整格式化小数部分的方法，例如添加前导零等。
    return hexFractional.toString(); // 直接返回原始字符串作为示例。
}

    public static String convertDecimalToHexBigEndian(Long  decimalNumber) {
        String hexRepresentation = Long.toHexString(decimalNumber); // 转换为十六进制字符串
        return hexRepresentation.toString();
    }
    public static String convertDecimalToHexBigEndian(Character  decimalNumber) {
        long bits = Double.doubleToLongBits(decimalNumber);
        String hexRepresentation = Long.toHexString(bits); // 转换为十六进制字符串
        // 转换为十六进制字符串
        return hexRepresentation.toString();
    }







    public static String toHexLittleEndian(int decimalNumber) {
        // 步骤1: 转换为大端模式十六进制字符串
        String hexString = Integer.toHexString(decimalNumber);

        return hexString.toString();
    }

    @Test
    public void aa() {
            String input = "1,2,3";
           Integer newSn =0;
        if (input.contains(",")){
            String lastCommaSeparatedString = getLastCommaSeparatedString(input);
            newSn= Integer.valueOf(lastCommaSeparatedString);
        }else {
            newSn= Integer.valueOf(input);
        }
        Integer size = 4;
        for (Integer i = 1; i < size; i++) {
            newSn++;
            String sn = getSn(newSn, i.toString());
            System.out.println(sn);
        }

        }

    public static String getSn(Integer newSn,String length) {

        StringBuffer snString =new StringBuffer();
        for (int i = 0; i < Integer.parseInt(length); i++) {
            snString.append(newSn+",");
            newSn++;
        }
        int lastIndex = snString.lastIndexOf(",");
        String  substring= snString.substring(0, lastIndex);


        return substring;
    }

        public static String getLastCommaSeparatedString(String input) {
            if (input == null || input.length() == 0) {
                return "";
            }

            int lastCommaIndex = input.lastIndexOf(",");
            if (lastCommaIndex == -1) {
                return "";
            }

            return input.substring(lastCommaIndex + 1);
        }



    @Test
    public void imageWordExport() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("de", "Easypoi");
        map.put("jd", "JueYue");
        map.put("time", "2024");
        WordImageEntity image = new WordImageEntity();
        image.setHeight(200);
        image.setWidth(500);
        String url = "https://static.jeecg.com/temp/国炬软件logo_1606575029126.png";
        byte[] netImgByUrl = getNetImgByUrl(url);
        image.setData(netImgByUrl);
//        image.setUrl("D:\\MY-XM\\codes\\ipds\\原型\\06.1 第一章内容.png");
        image.setType(WordImageEntity.Data);
        map.put("test", image);


        try {
            XWPFDocument doc = WordExportUtil.exportWord07(
                    "D:/MY-XM/codes/ipds/word/遥测通信协议(公开).docx", map);


            FileOutputStream fos = new FileOutputStream("D:\\MY-XM\\codes\\ipds\\word\\test.docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
